from rest_framework import permissions
from .models import Goods


class IsGoodsOwner(permissions.BasePermission):
    """
    自定义权限类，只允许货主本人修改自己的货源信息
    """

    def has_object_permission(self, request, view, obj):
        # 检查对象是否为Goods实例
        if isinstance(obj, Goods):
            # 只有货主本人才能修改货源信息
            return obj.user == request.user
        return False


class IsAuthenticatedShipper(permissions.BasePermission):
    """
    自定义权限类，只允许通过货主身份认证的用户进行操作
    """

    def has_permission(self, request, view):
        # 用户必须已认证
        if not request.user.is_authenticated:
            return False
            
        # 用户必须是货主角色且已通过认证
        return (
            request.user.role == request.user.Role.SHIPPER and 
            request.user.role_authstatus is True
        )


class IsOwnerAndShipper(permissions.BasePermission):
    """
    组合权限类，要求用户既是货主本人，又通过了货主身份认证
    """

    def has_object_permission(self, request, view, obj):
        # 检查对象是否为Goods实例
        if isinstance(obj, Goods):
            # 用户必须是货主本人且已通过认证
            return (
                obj.user == request.user and
                request.user.role == request.user.Role.SHIPPER and
                request.user.role_authstatus is True
            )
        return False